package carassius.GUI;

import carassius.BLL.AquavisieImporter;
import carassius.BLL.HideableListModel;
import carassius.BLL.FishPage;
import carassius.DAL.AnimalRow;
import carassius.DAL.Database;
import java.awt.Window;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.sql.SQLException;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.ResourceBundle;
import javax.swing.JCheckBox;
import javax.swing.JOptionPane;

public class OnlineAnimalImporterForm
		extends javax.swing.JDialog
{
	private ArrayList<FishPage> _dutchFishPages;
	private ArrayList<FishPage> _englishFishPages;
	private ArrayList<FishPage> _scientificFishPages;

	/** Creates new form OnlineAnimalImporterForm */
	public OnlineAnimalImporterForm(Window owner)
	{
		super(owner);
		initComponents();
		try
		{
			fetchDutchFishPages();
			fetchEnglishFishPages();
			fetchScientificFishPages();
		}
		catch (IOException ex)
		{
			uxDutchCheckBox.setSelected(false);
			JOptionPane.showMessageDialog(this,
					ResourceBundle.getBundle("carassius.resources.Messages").getString("NoInternetError"),
					ResourceBundle.getBundle("carassius.resources.Messages").getString("NoInternetErrorTitle"),
					JOptionPane.ERROR_MESSAGE);
		}
	}

	private synchronized void addFishPageToList(FishPage page)
	{
		HideableListModel model = (HideableListModel) uxAnimalList.getModel();
		String text = uxInputTextField.getText().toLowerCase();
		if (text != null && !text.isEmpty())
		{
			model.addElement(page, page.getName().toLowerCase().contains(text));
		}
		else
		{
			model.addElement(page);
		}
	}

	private synchronized void removeFishPageFromList(FishPage page)
	{
		HideableListModel model = (HideableListModel) uxAnimalList.getModel();
		model.removeElement(page);
	}

	private void fetchDutchFishPages() throws IOException
	{
		if (_dutchFishPages == null || _dutchFishPages.isEmpty())
		{
			_dutchFishPages = AquavisieImporter.getDutchNames();
		}
		for (FishPage page : _dutchFishPages)
		{
			addFishPageToList(page);
		}
	}

	private void fetchEnglishFishPages() throws IOException
	{
		if (_englishFishPages == null || _englishFishPages.isEmpty())
		{
			_englishFishPages = AquavisieImporter.getEnglishNames();
		}
		for (FishPage page : _englishFishPages)
		{
			addFishPageToList(page);
		}
	}

	private void fetchScientificFishPages() throws IOException
	{
		if (_scientificFishPages == null || _scientificFishPages.isEmpty())
		{
			_scientificFishPages = AquavisieImporter.getScientificNames();
		}
		for (FishPage page : _scientificFishPages)
		{
			addFishPageToList(page);
		}
	}

	private void removeDutchFishPages()
	{
		if (_dutchFishPages != null)
		{
			for (FishPage page : _dutchFishPages)
			{
				removeFishPageFromList(page);
			}
		}
	}

	private void removeEnglishFishPages()
	{
		if (_englishFishPages != null)
		{
			for (FishPage page : _englishFishPages)
			{
				removeFishPageFromList(page);
			}
		}
	}

	private void removeScientificFishPages()
	{
		if (_scientificFishPages != null)
		{
			for (FishPage page : _scientificFishPages)
			{
				removeFishPageFromList(page);
			}
		}
	}

	/** This method is called from within the constructor to
	 * initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is
	 * always regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        uxInputTextField = new TextFieldWithMenu();
        uxAnimalScrollPane = new javax.swing.JScrollPane();
        uxAnimalList = new javax.swing.JList();
        uxImportButton = new javax.swing.JButton();
        uxNamesPanel = new javax.swing.JPanel();
        uxDutchCheckBox = new javax.swing.JCheckBox();
        uxScientificCheckBox = new javax.swing.JCheckBox();
        uxEnglishCheckBox = new javax.swing.JCheckBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setName("Form"); // NOI18N
        getContentPane().setLayout(new java.awt.GridBagLayout());

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(carassius.CarassiusApp.class).getContext().getResourceMap(OnlineAnimalImporterForm.class);
        uxInputTextField.setText(resourceMap.getString("uxInputTextField.text")); // NOI18N
        uxInputTextField.setName("uxInputTextField"); // NOI18N
        uxInputTextField.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                uxInputTextFieldCaretUpdate(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.weightx = 1.0;
        getContentPane().add(uxInputTextField, gridBagConstraints);

        uxAnimalScrollPane.setName("uxAnimalScrollPane"); // NOI18N

        uxAnimalList.setModel(new HideableListModel());
        uxAnimalList.setName("uxAnimalList"); // NOI18N
        uxAnimalList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                uxAnimalListMouseClicked(evt);
            }
        });
        uxAnimalList.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                uxAnimalListKeyPressed(evt);
            }
        });
        uxAnimalScrollPane.setViewportView(uxAnimalList);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        getContentPane().add(uxAnimalScrollPane, gridBagConstraints);

        uxImportButton.setText(resourceMap.getString("uxImportButton.text")); // NOI18N
        uxImportButton.setName("uxImportButton"); // NOI18N
        uxImportButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                uxImportButtonActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTHEAST;
        getContentPane().add(uxImportButton, gridBagConstraints);

        uxNamesPanel.setName("uxNamesPanel"); // NOI18N
        uxNamesPanel.setLayout(new javax.swing.BoxLayout(uxNamesPanel, javax.swing.BoxLayout.LINE_AXIS));

        uxDutchCheckBox.setSelected(true);
        uxDutchCheckBox.setText(resourceMap.getString("uxDutchCheckBox.text")); // NOI18N
        uxDutchCheckBox.setName("uxDutchCheckBox"); // NOI18N
        uxDutchCheckBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nameToggled(evt);
            }
        });
        uxNamesPanel.add(uxDutchCheckBox);

        uxScientificCheckBox.setSelected(true);
        uxScientificCheckBox.setText(resourceMap.getString("uxScientificCheckBox.text")); // NOI18N
        uxScientificCheckBox.setName("uxScientificCheckBox"); // NOI18N
        uxScientificCheckBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nameToggled(evt);
            }
        });
        uxNamesPanel.add(uxScientificCheckBox);

        uxEnglishCheckBox.setSelected(true);
        uxEnglishCheckBox.setText(resourceMap.getString("uxEnglishCheckBox.text")); // NOI18N
        uxEnglishCheckBox.setName("uxEnglishCheckBox"); // NOI18N
        uxEnglishCheckBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nameToggled(evt);
            }
        });
        uxNamesPanel.add(uxEnglishCheckBox);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.gridheight = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.weightx = 1.0;
        getContentPane().add(uxNamesPanel, gridBagConstraints);

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void nameToggled(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nameToggled
	if (evt.getSource() instanceof JCheckBox)
	{
		Object source = evt.getSource();
		if (source.equals(uxDutchCheckBox))
		{
			if (!uxDutchCheckBox.isSelected())
			{
				if (!uxScientificCheckBox.isSelected())
				{
					uxEnglishCheckBox.setEnabled(false);
				}
				else if (!uxEnglishCheckBox.isSelected())
				{
					uxScientificCheckBox.setEnabled(false);
				}
				removeDutchFishPages();
				return;
			}
			else
			{
				try
				{
					fetchDutchFishPages();
				}
				catch (IOException ex)
				{
					uxDutchCheckBox.setSelected(false);
					JOptionPane.showMessageDialog(this,
							ResourceBundle.getBundle("carassius.resources.Messages").getString("NoInternetError"),
							ResourceBundle.getBundle("carassius.resources.Messages").getString("NoInternetErrorTitle"),
							JOptionPane.ERROR_MESSAGE);
				}
			}
		}
		else if (source.equals(uxScientificCheckBox))
		{
			if (!uxScientificCheckBox.isSelected())
			{
				if (!uxDutchCheckBox.isSelected())
				{
					uxEnglishCheckBox.setEnabled(false);
				}
				else if (!uxEnglishCheckBox.isSelected())
				{
					uxDutchCheckBox.setEnabled(false);
				}
				removeScientificFishPages();
				return;
			}
			else
			{
				try
				{
					fetchScientificFishPages();
				}
				catch (IOException ex)
				{
					uxScientificCheckBox.setSelected(false);
					JOptionPane.showMessageDialog(this,
							ResourceBundle.getBundle("carassius.resources.Messages").getString("NoInternetError"),
							ResourceBundle.getBundle("carassius.resources.Messages").getString("NoInternetErrorTitle"),
							JOptionPane.ERROR_MESSAGE);
				}
			}
		}
		else if (source.equals(uxEnglishCheckBox))
		{
			if (!uxEnglishCheckBox.isSelected())
			{
				if (!uxScientificCheckBox.isSelected())
				{
					uxDutchCheckBox.setEnabled(false);
				}
				else if (!uxDutchCheckBox.isSelected())
				{
					uxScientificCheckBox.setEnabled(false);
				}
				removeEnglishFishPages();
				return;
			}
			else
			{
				try
				{
					fetchEnglishFishPages();
				}
				catch (IOException ex)
				{
					uxEnglishCheckBox.setSelected(false);
					JOptionPane.showMessageDialog(this,
							ResourceBundle.getBundle("carassius.resources.Messages").getString("NoInternetError"),
							ResourceBundle.getBundle("carassius.resources.Messages").getString("NoInternetErrorTitle"),
							JOptionPane.ERROR_MESSAGE);
				}
			}
		}
		uxDutchCheckBox.setEnabled(true);
		uxScientificCheckBox.setEnabled(true);
		uxEnglishCheckBox.setEnabled(true);
	}
}//GEN-LAST:event_nameToggled

private void uxInputTextFieldCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_uxInputTextFieldCaretUpdate
	String text = uxInputTextField.getText().toLowerCase();
	HideableListModel<FishPage> model = (HideableListModel<FishPage>) uxAnimalList.getModel();
	if (!text.isEmpty())
	{
		Enumeration<FishPage> elements = model.elements();
		while (elements.hasMoreElements())
		{
			FishPage fp = elements.nextElement();
			model.setElementVisible(fp, fp.getName().toLowerCase().contains(text));
		}
	}
	else
	{
		model.setElementVisibleAll(true);
	}
}//GEN-LAST:event_uxInputTextFieldCaretUpdate

private void uxAnimalListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_uxAnimalListMouseClicked
	if (evt.getClickCount() == 2)
	{
		showCurrentSelectedFishPage();
	}
}//GEN-LAST:event_uxAnimalListMouseClicked

	private synchronized void showCurrentSelectedFishPage()
	{
		Object[] selectedValues = uxAnimalList.getSelectedValues();
		if (selectedValues.length == 1)
		{
			Object selectedValue = selectedValues[0];
			if (selectedValue instanceof FishPage)
			{
				try
				{
					FishPage page = (FishPage) selectedValue;
					AnimalRow animalRow = page.getAnimalRow();

					AnimalForm form = new AnimalForm(this, animalRow);
					form.setVisible(true);
				}
				catch (IOException ex)
				{
					JOptionPane.showMessageDialog(this,
							ResourceBundle.getBundle("carassius.resources.Messages").getString("NoInternetError"),
							ResourceBundle.getBundle("carassius.resources.Messages").getString("NoInternetErrorTitle"),
							JOptionPane.ERROR_MESSAGE);
				}
			}
		}
	}

	private void uxAnimalListKeyPressed(java.awt.event.KeyEvent evt)//GEN-FIRST:event_uxAnimalListKeyPressed
	{//GEN-HEADEREND:event_uxAnimalListKeyPressed
		switch (evt.getKeyCode())
		{
			case KeyEvent.VK_ENTER:
				showCurrentSelectedFishPage();
				break;
			case KeyEvent.VK_ESCAPE:
				uxAnimalList.clearSelection();
				break;
		}
	}//GEN-LAST:event_uxAnimalListKeyPressed

	private void uxImportButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_uxImportButtonActionPerformed
	{//GEN-HEADEREND:event_uxImportButtonActionPerformed
		Object[] selectedValues = uxAnimalList.getSelectedValues();
		if (selectedValues.length > 0)
		{
			ArrayList<SimpleEntry<FishPage, String>> failed = null;

			for (Object o : selectedValues)
			{
				if (o instanceof FishPage)
				{
					FishPage fp = (FishPage) o;
					try
					{
						AnimalRow animalRow = fp.getAnimalRow();
					}
					catch (Exception ex)
					{
						if (failed == null)
						{
							failed = new ArrayList<SimpleEntry<FishPage, String>>(1);
						}
						if (ex instanceof IOException)
						{
							failed.add(new SimpleEntry<FishPage, String>(fp, ResourceBundle.getBundle("carassius.resources.Messages").getString("SimpleNoInternetError")));
						}
						else if (ex instanceof SQLException)
						{
							failed.add(new SimpleEntry<FishPage, String>(fp, ResourceBundle.getBundle("carassius.resources.Messages").getString("AnimalSaveError")));
						}
					}
				}
			}
			if (failed != null)
			{
				StringBuilder sb = new StringBuilder(ResourceBundle.getBundle("carassius.resource.Messages").getString("ImportError"));
				for (SimpleEntry<FishPage, String> entry : failed)
				{
					sb.append("\n");
					sb.append(entry.getKey().toString());
					sb.append(": ");
					sb.append(entry.getValue());
				}
				JOptionPane.showMessageDialog(this, sb,
						ResourceBundle.getBundle("carassius.resources.Messages").getString("ImportErrorTitle"),
						JOptionPane.ERROR_MESSAGE);
			}
		}
	}//GEN-LAST:event_uxImportButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JList uxAnimalList;
    private javax.swing.JScrollPane uxAnimalScrollPane;
    private javax.swing.JCheckBox uxDutchCheckBox;
    private javax.swing.JCheckBox uxEnglishCheckBox;
    private javax.swing.JButton uxImportButton;
    private javax.swing.JTextField uxInputTextField;
    private javax.swing.JPanel uxNamesPanel;
    private javax.swing.JCheckBox uxScientificCheckBox;
    // End of variables declaration//GEN-END:variables
}
